package com.abc.filter;

import com.abc.config.CipherProperties;
import com.abc.config.PropertiesUtil;
import com.abc.util.SM2Utils;
import com.abc.util.Util;
import com.alibaba.fastjson.JSONObject;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 第三步：返回结果加密操作
 *
 * @Description APP端，接口返回的数据进行加密处理
 */
public class AppRespEncryptFilter implements GatewayFilter, Ordered {

    private int order;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 判断是否在白名单内，true为放行
        if (exchange.getAttributeOrDefault(ConstantFilter.WHITE_LIST_CONDITION, "false").equals("true")) {
            return chain.filter(exchange);
        }

        String bgDebug = exchange.getAttributeOrDefault(ConstantFilter.BG_DEBUG_KEY, ConstantFilter.REQ_RES_ENCRYPT);

        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {

                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);

                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        // 正常返回的数据
                        String rootData = new String(content, Charset.forName("UTF-8"));
                        byte[] respData = rootData.getBytes();

                        // todo fix: post请求只能返回json，get请求只能返回String
                        if (ConstantFilter.REQ_RES_ENCRYPT.equals(bgDebug) && "POST".equals(exchange.getRequest().getMethodValue())) {
                            // 对数据进行公钥加密
                            String encryptData = null;
                            try {
                                //String publicKey = "045E2EA23F09F2BF8AAFC38B2EC8CBC05631A44555E6A565435C833FF23CA9F5B43B406ABFE0016EF13E8B752E45B4A97A49033018C07ED993A21CB2F8E3187895";
                                //从配置文件获取key值
                                CipherProperties cipherProperties = PropertiesUtil.getCipherProperties();
                                String publicKey = cipherProperties.getPublicKey2();
                                encryptData = SM2Utils.encrypt(Util.hexToByte(publicKey), respData);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            JSONObject json = new JSONObject();
                            //json.put("k", "k");
                            json.put("data", encryptData);
                            respData = json.toJSONString().getBytes();
                        }

                        // 加密后的数据返回给客户端
                        byte[] uppedContent = new String(respData, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public AppRespEncryptFilter(int order) {
        this.order = order;
    }
}